package fr.axones.pocketagile.ui.controler.command.project
{	
	import fr.axones.pocketagile.services.remote.AuthenticationService;
	import fr.axones.pocketagile.services.remote.ProjectService;
	import fr.axones.pocketagile.ui.controler.Controler;
	import fr.axones.pocketagile.ui.model.Model;
	import fr.axones.pocketagile.ui.view.authentication.AuthenticationEvent;
	import fr.axones.pocketagile.ui.view.main.project.ProjectEvent;
	import fr.axones.pocketagile.vo.ProjectVO;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class ProjectGetAllCommand
	{
		[Inject(id='projectService')]
		public var projectService:ProjectService;
		
		[Inject(id='controler')]
		public var controler:Controler;
		
		[Inject(id='model')]
		public var model:Model;
		
		public static const SUCCESS:String = "successGetProjects";
		
		public static const ERROR_UNKNOW:String = "unknowGetProjects";
		public static const ERROR_CONNECTION:String = "connectionGetProjects";
		
		public function ProjectGetAllCommand()
		{
		}
		
		[Command(selector="getProjects")]
		public function execute(event:ProjectEvent):AsyncToken
		{				
			return projectService.getProjects(model.user.id);
		}
		
		[CommandResult(selector="getProjects")]
		public function result(result:ResultEvent,event:ProjectEvent):void
		{			
			if(result.result.status<300 && result.result.status>=200)
			{
				var projects:ArrayCollection = ProjectVO.builds(result.result.data)
				model.projects = projects;			
				
				if(model.project != null)
				{
					for each(var project:ProjectVO in model.projects)
					{
						if(project.id == model.project.id)
						{
							model.project = project;
						}
					}
				}
				
				controler.throwSuccess(SUCCESS,projects,result.result.status);
			}
			else
			{
				controler.throwError(ERROR_UNKNOW,null,1);
			}
		}
		
		[CommandError(selector="getProjects")]
		public function fault(fault:FaultEvent,event:ProjectEvent):void
		{
			controler.throwError(ERROR_CONNECTION,null,0);
		}
	}
}